<?php

namespace App\Web\Model;

use EchoPHP\Facades\Redis;

class MySearch extends Model {
    private $searchNum = 10; //每个人最多5个搜索器
    private $redisName = 'mysearch';

    /**
     * 添加搜索器
     * @param $oprId
     * @param $params
     * @return array
     */
    public function addSearch($oprId, $params) {

        //校验输入字段的长度
        if (empty($params['searchname']) || mb_strlen($params['searchname']) > 50) {
            return ['status' => false, 'message' => '搜索器名称不能超过50个字且不能为空'];
        }
        if (!empty($params['fulltext']) && mb_strlen($params['fulltext']) > 50) {
            return ['status' => false, 'message' => '关键字/ID不能超过50个字'];
        }
        if (!empty($params['cotext']) && mb_strlen($params['cotext']) > 50) {
            return ['status' => false, 'message' => '公司名称不能超过50个字'];
        }

        //每个人保存搜索器数量限制
        $redisClient = Redis::connect($this->redisName);
        $key = $this->getKey($oprId);
        $count = $redisClient->hlen($key);
        if ($count >= $this->searchNum) {
            return ['status' => false, 'message' => '最多保存' . $this->searchNum . '个搜索器'];
        }

        //搜索器不可以重名
        $list = $this->getSearchList($oprId);
        if (!empty($list)) {
            foreach ($list as $v) {
                if ($v['searchname'] == $params['searchname']) {
                    return ['status' => false, 'message' => '搜索器名称不能重复'];
                }
            }
        }
        $score = time();
        $params['searchid'] = $score;
        $result = $redisClient->hSet($key, $score, json_encode($params));
        if ($result === false) {
            return ['status' => false, 'message' => '保存失败'];
        }
        return ['status' => true, 'message' => '保存成功'];

    }

    /**
     * 获取完整的搜索器列表信息
     * @param $oprId
     * @return array
     */
    public function getSearchList($oprId) {
        if (empty($oprId)) {
            return [];
        }
        $redisClient = Redis::connect($this->redisName);
        $searchInfo = $redisClient->hGetAll($this->getKey($oprId));
        $list = [];
        if ($searchInfo) {
            foreach ($searchInfo as $k => $v) {
                $list[$k] = json_decode($v, true);
            }
            krsort($list);
        }
        return $list;
    }

    public function deleteSearch($oprId, $searchId) {
        if (empty($oprId) || empty($searchId)) {
            return ['status' => false, 'message' => '请指定需要删除的搜索器'];
        }
        $redisClient = Redis::connect($this->redisName);
        $result = $redisClient->hdel($this->getKey($oprId), $searchId);
        return ['status' => $result, 'message' => $result ? ' 删除成功' : '删除失败'];
    }

    public function getKey($key) {
        return 'mysearch:' . $key;
    }
}